import 'dart:io';
import 'dart:math';
import 'package:image_picker/image_picker.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:note/common/common.dart';
import 'package:note/common/tools.dart';
import 'package:note/manager/global.dart';
import 'package:note/models/appSetModel.dart';
import 'package:note/widgets/dialog.dart';
import 'state.dart';

class SetAppLogic extends GetxController {
  final SetAppState state = SetAppState();

  @override
  void onInit() {
    super.onInit();
    final set = GlobalUtil.appSet.value;
    state.nameController.text = set.userName;
    state.bgImg.value = File(set.bgImgPath ?? '');
  }

  @override
  void dispose() {
    state.dispose();
    super.dispose();
  }

  Future<void> onSave() async {
    AppSetModel set = AppSetModel(
      userName: state.nameController.text,
    );
    //保存背景
    if (state.bgImg.value.existsSync() && state.selectedBG) {
      //找到项目文件夹
      final directory = FilePath.getAppDirectory;
      // 生成随机的整数作为文件名的一部分
      int randomInt = Random().nextInt(100000);
      final String newBGPath =
          '$directory/${FilePath.bgImage(randomInt.toString())}';
      //保存本地
      await state.bgImg.value.copy(newBGPath);
      //删除文件
      state.bgImg.value.delete();
      if (File(GlobalUtil.appSet.value.bgImgPath ?? '').existsSync()) {
        File(GlobalUtil.appSet.value.bgImgPath ?? '').deleteSync();
      }
      set.bgImgPath = newBGPath;
    } else if (state.deletedBg) {
      //删除bg文件
      state.bgImg.value.delete();
      File(GlobalUtil.appSet.value.bgImgPath ?? '').deleteSync();
      set.bgImgPath = '';
    }
    GlobalUtil.setAppSet(set);
    Toasts.showToast(Strings.saveSuccess);
    Get.back();
  }

  void onSelectBG() async {
    if (state.nameFocus.hasFocus) {
      cancelFocus();
      return;
    }
    XFile? imageFile = await ImagePicker()
        .pickImage(source: ImageSource.gallery, imageQuality: 100);
    if (imageFile == null) {
      Toasts.showToast('未选择图片');
      return;
    } else {
      state.bgImg.value = File(imageFile.path);
      state.selectedBG = true;
      state.deletedBg = false;
    }
  }

  void cancelFocus() {
    FocusManager.instance.primaryFocus?.unfocus();
  }

  void onDeleteBG() {
    if (!state.bgImg.value.existsSync()) {
      Toasts.showToast('还没有设置背景图');
      return;
    }
    Get.dialog(defaultDialog(
        title: Strings.tip,
        content: '确定要删除背景吗？',
        sureFunction: () {
          state.bgImg.value = File('');
          state.deletedBg = true;
          Toasts.showToast('已删除，保存后生效');
        }));
  }

  void onCleanName() {
    state.nameController.text = '';
  }
}
